package com.gnote.repair.service.impl;

import com.alibaba.fastjson.JSON;
import com.gnote.repair.domain.LoginUser;
import com.gnote.repair.domain.ResponseResult;
import com.gnote.repair.domain.SysUser;
import com.gnote.repair.service.LoginService;
import com.gnote.repair.service.SysUserService;
import com.gnote.repair.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Gnote
 * @since 2025/3/5 16:05
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final RedisTemplate<String, String> redisTemplate;
    private final PasswordEncoder passwordEncoder;
    private final SysUserService sysUserService;

    @Override
    public String login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (ObjectUtils.isEmpty(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        LoginUser user = (LoginUser) authenticate.getPrincipal();
        //将登录信息存入redis
        redisTemplate.opsForValue().set("login:" + user.getSysUser().getId(), JSON.toJSONString(user));
        return JwtUtil.createJWT(String.valueOf(user.getSysUser().getId()));
    }


    @Override
    public String logout() {
        // 防御性获取上下文
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 双重校验机制
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();

            // 类型安全校验
            if (principal instanceof LoginUser) {
                LoginUser loginUser = (LoginUser) principal;
                Long userId = loginUser.getSysUser().getId();

                // 异步清理Redis记录
                redisTemplate.delete("login:" + userId);

            }
        }

        // 彻底清除安全上下文
        SecurityContextHolder.clearContext();

        return "登出成功";
    }

    @Override
    public ResponseResult<String> register(LoginUser loginUser) {
        String encode = passwordEncoder.encode(loginUser.getSysUser().getPassword());
        //加密
        SysUser sysUser = loginUser.getSysUser();
        sysUser.setPassword(encode);
        sysUserService.save(sysUser);
        return new ResponseResult<>(200, "注册成功");
    }


}
